import wx
import sys
import os
import clips
from eRecruiterObjects import * 
from ExplanationFrame import ExplanationFrame
from ResumeFrame import ResumeFrame
from eRecruiterEducationDialog import EducationDialog


class eRecruiterFrame(wx.Frame):
    def __init__(self, title = "eRecruiter"):
        wx.Frame.__init__(self, None,-1,title,pos=(150,150), size=(800,700))
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.areas = []
        self.area_weights = AreaWeightObject()
        
        self.certifications = ['A+','Network+','CCENT','CCNA','CCNP','CCIE','MCSD']
        self.certifications.sort()
            
        vbox1 = wx.BoxSizer(wx.VERTICAL)
        hbox  = wx.BoxSizer(wx.HORIZONTAL)

        panel2 = wx.Panel(self, -1, style=wx.NO_BORDER, pos=(1,1), size=(780,200))
        panel3 = wx.Panel(self, -1, style=wx.NO_BORDER, pos=(1,1), size=(780,200))
        panel = wx.Panel(self, -1, size=(780,400))
        groupBoxQUAL = wx.StaticBox(panel2,-1,'Qualities',(3,3),size=(780,195))
        groupBoxSKILL = wx.StaticBox(panel3,-1,'Skills',(3,3),size=(780,195))
        vbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 0)
        vbox1.Add(panel3,1,wx.EXPAND | wx.ALL, 0)
        vbox1.Add(panel, 1, wx.EXPAND | wx.ALL, 0)

        
        

        self.edulevel = wx.StaticText(panel2, -1, 'Education Level', (450,25))
        self.edulevel.SetToolTip(wx.ToolTip("What is the maximum level of education that we should give points for.  You will be able to set the required level after clicking find resumes."))
        wx.StaticLine(panel2, -1, (447, 40), (100,1))
        self.Edu_rb1 = wx.RadioButton(panel2, -1, 'High School', (450, 45), style=wx.RB_GROUP)
        self.Edu_rb2 = wx.RadioButton(panel2, -1, 'Associates', (450, 60))
        self.Edu_rb3 = wx.RadioButton(panel2, -1, 'Bachelors', (450, 75))
        self.Edu_rb4 = wx.RadioButton(panel2, -1, 'Masters', (450, 90))
        self.Edu_rb5 = wx.RadioButton(panel2, -1, 'PhD', (450, 105))
        

        edulevel = wx.StaticText(panel2, -1, 'Topics to Consider', (20,25))
        wx.StaticLine(panel2, -1, (17, 40), (175,1))
        self.ldrExperCHK = wx.CheckBox(panel2, -1 ,'Leadership Experiences', (20, 45))
        self.ldrExperCHK.SetToolTip(wx.ToolTip("Should we score based on how much leadership experience they have?"))
        self.desCertCHK = wx.CheckBox(panel2, -1 ,'Desired Certifications', (20, 60))
        self.desCertCHK.SetToolTip(wx.ToolTip("Should we score based on whether or not they have some of the desired certifications"))
        self.desSkillsCHK = wx.CheckBox(panel2, -1 ,'Desired Skills', (20, 75))
        self.desSkillsCHK.SetToolTip(wx.ToolTip("Should we score based on whether or not they have some of the desired Skills"))
        self.desEduCHK = wx.CheckBox(panel2, -1 ,'Education Facts', (20, 90))
        self.desEduCHK.SetToolTip(wx.ToolTip("Should we score based on secondary education facts, like school and a minimum GPA"))
        self.desWorkAreaCHK = wx.CheckBox(panel2, -1 ,'Areas of Expertise', (20, 105))
        self.desWorkAreaCHK.SetToolTip(wx.ToolTip("Should we score based on keywords relating to work experience found in their resume"))

            
        wx.StaticText(panel2,-1,'General Keywords',(570,25))
        wx.StaticLine(panel2, -1, (567, 40), (185,1))
        self.KeyWordsTEXTBOX = wx.TextCtrl(panel2, -1,pos=(570,45),size=(180,80),style=wx.TE_MULTILINE)

        wx.StaticText(panel2,-1,'Years Experience:',(570,130))
        wx.StaticLine(panel2, -1, (567, 145), (100,1))
        self.YearsExpTEXTBOX = wx.TextCtrl(panel2, -1,pos=(570,150),size=(100,-1))
                

        wx.StaticText(panel2,-1,'Certifications',(225,25))
        self.CertificationsBox = wx.ListBox(panel2, -1,(225, 45),(200,80),self.certifications, style=wx.LB_MULTIPLE)        
        wx.StaticLine(panel2, -1, (223, 40), (210,1))
        wx.StaticText(panel2,-1,'Non-Listed Certifications:',(225,130))
        wx.StaticLine(panel2, -1, (223, 145), (210,1))
        self.NonListedCertTEXTBOX = wx.TextCtrl(panel2, -1,pos=(225,150),size=(200,40),style=wx.TE_MULTILINE)
        
        wx.StaticText(panel3,-1,'Required',(10,20))
        self.ReqSkillsTEXTBOX = wx.TextCtrl(panel3, -1,pos=(10,35),size=(755,70),style=wx.TE_MULTILINE)
        wx.StaticText(panel3,-1,'Desired',(10,105))
        self.DesSkillsTEXTBOX = wx.TextCtrl(panel3, -1,pos=(10,120),size=(755,70),style=wx.TE_MULTILINE)

        wx.StaticText(panel2,-1,'Min GPA:',(450,130))
        wx.StaticLine(panel2, -1, (447, 145), (100,1))
        self.MinGpaTEXTBOX = wx.TextCtrl(panel2, -1,pos=(450,150),size=(100,-1))
        

        self.resetBTN = wx.Button(panel, -1, "Reset System", (685,15))
        self.findBTN = wx.Button(panel, -1, "Find Resumes", (585,15))
        
        self.ResultList = wx.ListCtrl(panel, 26, pos=(5,45), size=(775,210),
                                      style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.ResultList.SetBackgroundColour(wx.Colour(200, 200, 200))
        self.ResultList.InsertColumn(0,"Name")
        self.ResultList.InsertColumn(1,"Match Score")
        self.ResultList.InsertColumn(2,"ID")
        self.ResultList.InsertColumn(3,"Resume File Location")
        self.ResultList.InsertColumn(4,"Total Keyword Occurences")
        self.ResultList.SetColumnWidth(0, 150)
        self.ResultList.SetColumnWidth(1, 100)
        self.ResultList.SetColumnWidth(2,75)
        self.ResultList.SetColumnWidth(3,240)
        self.ResultList.SetColumnWidth(4,200)
        
        self.ResultList.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.showPopupMenu)    
        
        hbox.Add(vbox1, 1, wx.EXPAND)
        self.SetSizer(hbox)
        
            
    def showPopupMenu(self, event):
        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            # make a menu
        menu = wx.Menu()
        explanItem = wx.MenuItem(menu, self.popupID1,"Get Explanation")
        menu.AppendItem(explanItem)
        menu.Append(self.popupID2, "See Resume")

        wx.EVT_MENU(self, self.popupID1, self.DisplayExplanation )
        wx.EVT_MENU(self, self.popupID2, self.DisplayResume )
 
        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(menu)
        menu.Destroy()

    def DisplayResume(self, event):
        item = self.ResultList.GetFirstSelected()
        if item != -1:
            name = self.ResultList.GetItemText(item)
            li = self.ResultList.GetItem(item,3)
            res_loc = li.GetText()
            top = ResumeFrame(res_loc,"Resume For " + name)
            top.Show()
            

    def DisplayExplanation(self, event):
        item = self.ResultList.GetFirstSelected()
        if item != -1:
            name = self.ResultList.GetItemText(item)
            li = self.ResultList.GetItem(item,2)
            personID = li.GetText()
            print personID
            
            explanations =  []
            try:
                explan_facts = clips.Eval("(find-all-facts ((?f Explanation)) (eq ?f:ID %s))" %(personID))
            except:
                print 'no explanations'
                explan_facts = []
            #go through list of explanations and match them up in categories

             #figure out the good ones
            person_facts = clips.Eval("(find-all-facts ((?f Person)) (eq ?f:ID %s ))" %(personID))
            person = person_facts[0]

            cert_val = 0
            AOE_val = 0
            edu_val = 0
            skill_val = 0
            ldr_val = 0
            
            if 'AreasOfExpertise' in self.areas:
                AOE_val =  self.area_weights.AreasOfExpertise[2]
                
            if 'Education' in self.areas:
                edu_val = self.area_weights.Education[1]
                
            if 'Certifications' in self.areas:
                cert_val = self.area_weights.Certs[1]
                
            if 'Skills' in self.areas:
                skill_val = self.area_weights.Skills[1]
                
            if 'Leadership' in self.areas:
                ldr_val = self.area_weights.Leadership[1]

            total = AOE_val + ldr_val + skill_val + cert_val + edu_val

            if total == 0:
                total = 1


            skill_explans = []
            cert_explans = []
            edu_explans = []
            work_area_explans = []
            degree_explans = []
            leader_explans = []
            years_exp_explans = []
            
            if self.area_weights.AreasOfExpertise is not None:
                for fact in explan_facts:
                    if fact.Slots['section'] == 'Work Area':
                        work_area_explans.append(fact.Slots['explanation'])
                if person.Slots['WorkAreaScore'] >= 0:
                    work_area_explans.append('This applicant has all of the required work areas')
                explanations.append(QualityExplanation("Work Area Expereinces", person.Slots['WorkAreaScore'],work_area_explans))

            if self.area_weights.Education is not None:
                for fact in explan_facts:
                    if fact.Slots['section'] == 'Degree':
                        degree_explans.append(fact.Slots['explanation'])
                if person.Slots['DegreeScore'] >= 0:
                    degree_explans.append('This applicant meets the minimum degree levels')
                explanations.append(QualityExplanation("Degree", person.Slots['DegreeScore'],degree_explans))
            


            # get the bad facts from system
            for fact in explan_facts:
                if fact.Slots['section'] == 'Skill':
                    skill_explans.append(fact.Slots['explanation'])
                elif fact.Slots['section'] == 'Certification':
                    cert_explans.append(fact.Slots['explanation'])
                elif fact.Slots['section'] == 'Education':
                    edu_explans.append(fact.Slots['explanation'])
                elif fact.Slots['section'] == 'Leadership':
                    leader_explans.append(fact.Slots['explanation'])
                elif fact.Slots['section'] == 'Total Experience':
                    years_exp_explans.append(fact.Slots['explanation'])

            
            
            if self.area_weights.Loyalty is not None:
                if self.area_weights.Loyalty[3] == 1:
                    if self.area_weights.Loyalty[0] >= person.Slots['LoyaltyScore']:
                        explanations.append(QualityExplanation("Loyalty",person.Slots["LoyaltyScore"],['This applicant meets your requirments for average time spent at a job with an average of %s years'%(self.area_weights.Loyalty[0])]))
                elif self.area_weights.Loyalty[3] == 0:
                    if self.area_weights.Loyalty[0] <= person.Slots['LoyaltyScore']:
                        explanations.append(QualityExplanation("Adaptability",person.Slots["LoyaltyScore"],['This applicant meets your requirments for average time spent at a job with an average of %s years'%(self.area_weights.Loyalty[0])]))
                                            
            if person.Slots['SkillScore'] >= 0:
                skill_explans.append('This applicant has all of the required skills')
            if person.Slots['CertificationScore'] >= 0:
                cert_explans.append('This applicant has all of the required certifications')
            if person.Slots['EducationScore'] >= 0:
                edu_explans.append('This applicant has all of the required education information')


            try:
                keyword_facts = clips.Eval("(find-all-facts ((?f KeyWordOccurance)) (eq ?f:ID %s))" %(personID))
            except:
                print 'no keywords'
                keyword_facts = []

            keyword_explan = []
            
            for key_fact in keyword_facts:
                keyword_explan.append("The keyworld %s appeared in the resume %s times"%(key_fact.Slots['Phrase'],key_fact.Slots['Count']))
            

            if self.area_weights.Leadership is not None:
                if person.Slots['LeadershipScore'] < (self.area_weights.Leadership[0]*ldr_val/total):
                    leader_explans.append("This applicant did not meet the threshold you set for their leadership experience to count")                              
                    explanations.append(QualityExplanation("Leadership",0.0,leader_explans))
                else:
                    explanations.append(QualityExplanation("Leadership",person.Slots['LeadershipScore'],leader_explans))
            
            
            if self.area_weights.Skills is not None:
                if person.Slots['SkillScore'] < (self.area_weights.Skills[0]*skill_val/total):
                    skill_explans.append("This applicant did not meet the threshold you set for their Skill score to count")
                    explanations.append(QualityExplanation("Skills",0.0,skill_explans))
                else:
                    explanations.append(QualityExplanation("Skills",person.Slots['SkillScore'],skill_explans))
            else:
                skill_explans.append("You did not select for this applicants skills to count towards thier score")
                explanations.append(QualityExplanation("Skills",0.0,skill_explans))
                                          
            if self.area_weights.Certs is not None:
                if person.Slots['CertificationScore'] < (self.area_weights.Certs[0]*cert_val/total):
                    cert_explans.append("This applicant did not meet the threshold you set for thier certification score to count")
                    explanations.append(QualityExplanation("Certifications",0.0,cert_explans))
                else:
                     explanations.append(QualityExplanation("Certifications",person.Slots['CertificationScore'],cert_explans))
            else:
                cert_explans.append("You did not select for this applicants certifications to count towards thier score")
                explanations.append(QualityExplanation("Certifications",0.0,cert_explans))
            
            
            explanations.append(QualityExplanation("Education",person.Slots['EducationScore'],edu_explans))

            if len(keyword_explan) > 0:
                explanations.append(QualityExplanation("Keywords",'',keyword_explan))

            explanations.append(QualityExplanation("Years of Experience",'',years_exp_explans))

            top = ExplanationFrame(explanations, "Explanations for " + name)
            top.Show()

    def DisplayResults(self,resultList):
        if self.ResultList.GetItemCount() > 0:
            self.ResultList.DeleteAllItems()
        id = wx.NewId()
        for result in resultList:
            pos = self.ResultList.InsertStringItem(id, result.Name)
            self.ResultList.SetStringItem(pos,1,result.Score)
            self.ResultList.SetStringItem(pos,2,result.ID)
            self.ResultList.SetStringItem(pos,3,result.ResumeLocation)
            self.ResultList.SetStringItem(pos,4,result.KeyCount)

    def RetrieveRequiredSkills(self):        
        reqSkills = self.ReqSkillsTEXTBOX.GetValue().replace('\n',',').lower().split(',')
        reqSkills = [s.lstrip().rstrip() for s in reqSkills]
        if '' in reqSkills:
            reqSkills.remove('')
        return reqSkills

    def RetrieveDesiredSkills(self):
        desSkills = self.DesSkillsTEXTBOX.GetValue().replace('\n',',').lower().split(',')
        desSkills = [s.lstrip().rstrip() for s in desSkills]
        if '' in desSkills:
            desSkills.remove('')
        return desSkills

    def RetrieveCertifications(self):
        neces = []
        non_select = self.NonListedCertTEXTBOX.GetValue().replace('\n',',').lower().split(',')
        non_select = [s.lstrip().rstrip() for s in non_select]
        if '' in non_select:
            non_select.remove('')
        cert_pos = self.CertificationsBox.GetSelections()
        cert = [self.certifications[x] for x in cert_pos]
        all_certs = cert + list(set(non_select) - set(cert)) 

        if len(all_certs) > 0:
            dlg = wx.MultiChoiceDialog( self,
                                       "Please Select the Required Certifications",
                                       "Certifications", all_certs)
     
            if (dlg.ShowModal() == wx.ID_OK):
                selections = dlg.GetSelections()
                neces = [all_certs[x] for x in selections]
        return [all_certs, neces]

    def RetrieveKeywords(self):
        keywords = self.KeyWordsTEXTBOX.GetValue().replace('\n',',').lower().split(',')
        keywords = [s.lstrip().rstrip() for s in keywords]
        if '' in keywords:
            keywords.remove('')
        return keywords

    def RetrieveMinGPA(self):
        gpa = 0.0
        try:
            gpa = float(self.MinGpaTEXTBOX.GetValue())
        except ValueError:
            print "GPA is not a numeric string."
            gpa = 0.0
        print gpa
        return gpa

    def RetrieveYearsExpereience(self):
        years = [0,0]
        year_string = self.YearsExpTEXTBOX.GetValue().replace(' ','')
        if '-' in year_string:
            try:
                years = [ float(s) for s in year_string.split('-')]
            except:
                print "Years Experience not fomatted properly"
                years = [0,0]
            if len(years) != 2:
                print 'Years Experience not formatted properly.  Must be of the form "Years Min" or "Years Min - Years Max"'
                years = [0,0]
        else:
            try:
                years[0] = float(year_string)
            except:
                print "Years Expereience not formatted properly"
                years = [0,0]
        return years

    def GetValues(self,event):
        self.min_edu = self.eduDia.GetMinEducation()
        self.eduDia.Close()
        return True
    
    def RetrieveEducationLevel(self):
        max_ranking = 0
        eduLevel = []
        if self.Edu_rb1.GetValue():
            max_ranking = 1
            eduLevel.append("Highschool")
        elif self.Edu_rb2.GetValue():
            max_ranking = 2
            eduLevel.append("Highschool")
            eduLevel.append("Associates")
        elif self.Edu_rb3.GetValue():
            max_ranking = 3
            eduLevel.append("Highschool")
            eduLevel.append("Associates")
            eduLevel.append("Bachelors")
        elif self.Edu_rb4.GetValue():
            max_ranking = 4
            eduLevel.append("Highschool")
            eduLevel.append("Associates")
            eduLevel.append("Bachelors")
            eduLevel.append("Masters")
        elif self.Edu_rb5.GetValue():
            max_ranking = 5
            eduLevel.append("Highschool")
            eduLevel.append("Associates")
            eduLevel.append("Bachelors")
            eduLevel.append("Masters")
            eduLevel.append("PhD")

        self.eduDia = EducationDialog(eduLevel)
        self.eduDia.findBTN.Bind(wx.EVT_BUTTON, self.GetValues)
            #show modal will wait till we click ok or (x)
        self.eduDia.ShowModal()
        
        
        return [max_ranking, self.min_edu ]

    #def RetrieveSliderValues(self):
     #   val_dict = { 'Leadership':0,'Intelligence':0}
      #  val_dict['Leadership'] = self.LeadershipSLD.GetValue()
      #  val_dict['Intelligence'] = self.IntelligenceSLD.GetValue()
      #  print val_dict
      #  return val_dict
        
    def OnClose(self, event):
        self.Destroy()



        
